﻿using CommonEngine.Helper;
using CommonEngine.Security;
using CommonFP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace CommonEngine
{
    /// <summary>
    /// 常用公共类
    /// </summary>
    public static class CommonOP
    {
        /// <summary>
        /// 生成密钥
        /// </summary>
        public static string MakeSecretkey()
            => Md5Helper.Encrypt(CommonOP.CreateNo(), 16).ToLower();

        /// <summary>
        /// Token解密出账号
        /// </summary>
        public static string TokenDecrypt(string token, string Secretkey)
        {
            if (token.IsEmpty() || Secretkey.IsEmpty())
                return string.Empty;

            try
            {
                var DES = DESEncrypt.Decrypt(token);
                string PublicKey = DES.Substring(0, DES.Length - 4);
                string code = PublicKey.Replace(Secretkey, "").Trim();
                return code;
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 账号加密成Token
        /// </summary>
        public static string TokenEncrypt(string account, string Secretkey)
        {
            if (account.IsEmpty() || Secretkey.IsEmpty())
                return string.Empty;

            string PublicKey = account + " " + Secretkey + " " + CommonOP.RNGRandomInt().ToString();
            string Token = DESEncrypt.Encrypt(PublicKey);
            return Token;
        }

        #region---仪表计时器---

        /// <summary>
        /// 计时器开始
        /// </summary>
        public static Stopwatch TimerStart()
        {
            Stopwatch watch = new Stopwatch();
            watch.Reset();
            watch.Start();
            return watch;
        }
        /// <summary>
        /// 计时器结束
        /// </summary>
        public static string TimerEnd(Stopwatch watch)
        {
            watch.Stop();
            double costtime = watch.ElapsedMilliseconds;
            return costtime.ToString();
        }

        /// <summary>
        /// 跟踪记录OP操作用时(返回元组)
        /// </summary>
        public static (T, string) Trace<T>(string op, Func<T> f)
        {
            var sw = new Stopwatch();
            sw.Start();

            T t = f();

            sw.Stop();
            return (t, $"{op} took {sw.ElapsedMilliseconds}ms");
        }
        /// <summary>
        /// 跟踪OP操作
        /// </summary>
        public static T Trace<T>(Action<string> log, string op, Func<T> f)
        {
            log($"Entering {op}");

            T t = f();

            log($"Leaving {op}");
            return t;
        }

        #endregion

        #region---流操作---

        /// <summary>
        /// 读取文件字节流(WebAPI上下文不适用)
        /// </summary>
        public static byte[] GetBytesByPath(string path)
        {
            string pathServer = path;
            byte[] bytes = null;
            if (!File.Exists(pathServer))
                return bytes;

            return FP.Try(() => FP.Using(new FileStream(pathServer, FileMode.Open, FileAccess.Read),
                fs => FP.Using(new BinaryReader(fs),
                br => br.ReadBytes((int)fs.Length))))
                .Run().Match(e => null, a => a);
        }
        /// <summary>
        /// 文本内容转为传输字节流
        /// </summary>
        public static byte[] GetPassData(string Content)
        {
            if (string.IsNullOrEmpty(Content))
                return null;

            string data = ConvertStringToBase64(ConvertStringEncode(Content));
            return Convert.FromBase64String(data);
        }
        /// <summary>
        /// 传输字节流转为文本内容
        /// </summary>
        public static string GetPassResult(byte[] data)
        {
            if (data == null)
                return string.Empty;

            var str = Convert.ToBase64String(data);
            return ConvertStringDecode(ConvertBase64ToString(str));
        }

        #endregion

        #region---常用操作---

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip">ip地址字符串</param>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 删除数组中的重复项
        /// </summary>
        /// <param name="values">重复值</param>
        /// <returns></returns>
        public static string[] RemoveDup(string[] values)
        {
            List<string> list = new List<string>();
            for (int i = 0; i < values.Length; i++)//遍历数组成员
            {
                if (!list.Contains(values[i]))
                {
                    list.Add(values[i]);
                };
            }
            return list.ToArray();
        }

        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            Random random = new Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        /// <param name="str">字串</param>
        /// <returns></returns>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        /// <param name="str">字串</param>
        /// <param name="strchar">指定的字符</param>
        /// <returns></returns>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        /// <summary>
        /// 删除最后结尾的长度
        /// </summary>
        /// <param name="str">字串</param>
        /// <param name="Length">删除长度</param>
        /// <returns></returns>
        public static string DelLastLength(string str, int Length)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            str = str.Substring(0, str.Length - Length);
            return str;
        }


        /// <summary>
        /// int转时间
        /// </summary>
        public static DateTime GetDTByInt(int i)
        {
            Int64 begtime = Convert.ToInt64(i) * 10000000;  //100毫微秒为单位,textBox1.text需要转化的int日期
            DateTime dt_1970 = new DateTime(1970, 1, 1, 8, 0, 0);
            long tricks_1970 = dt_1970.Ticks;   //1970年1月1日刻度
            long time_tricks = tricks_1970 + begtime;   //日志日期刻度
            DateTime dt = new DateTime(time_tricks);    //转化为DateTime
            return dt.Date;   //获取到日期整数---//输出值只精确到天
        }

        /// <summary>
        /// 时间转int---int n = 1999999999; int的最大值为2147483647---11位
        /// </summary>
        public static int GetIntByDT(DateTime dt)
        {
            int result = 0;
            DateTime startdate = new DateTime(1970, 1, 1, 8, 0, 0);
            //long l = DateTime.Now.Ticks;  //---时间唯一码---
            //TimeSpan seconds = end.AddDays(1) - startdate;  //---这样写---输出值被精确到秒
            DateTime end = new DateTime(dt.Year, dt.Month, dt.Day); //只精确到天
            TimeSpan seconds = end - startdate;
            result = Convert.ToInt32(seconds.TotalSeconds);
            return result;
        }

        /// <summary>
        /// 时间戳还原
        /// </summary>
        public static DateTime GetDTByUnixTime(string UnixTime)
        {
            DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            DateTime TranslateDate = startTime.AddSeconds(double.Parse(UnixTime));
            return TranslateDate;
        }

        /// <summary>
        /// DateTime转Unix时间戳
        /// </summary>
        public static long GetUnixTimeByDT(DateTime? dt = null)
        {
            DateTime DateNow = dt == null ? DateTime.Now : dt.Value;
            long UnixDate = (DateNow.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            return UnixDate;
        }


        /// <summary>
        /// 判断字符串是否是数字字符串
        /// </summary>
        public static bool IsInterger(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            else
            {
                foreach (char c in str)
                {
                    if (char.IsNumber(c))
                        continue;
                    else
                        return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 取出字符串中，数字字符串的部分
        /// </summary>
        public static string GetIntergerStr(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            else
            {
                string result = Regex.Replace(str, @"[^0-9]+", "");
                return result;
            }
        }

        /// <summary>
        /// 将数据库中timespan转换成十六进制字符串
        /// </summary>
        /// <param name="objTs">从数据库中获取的timespan值</param>      
        /// <returns>timespan十六进制字符串</returns>
        public static string ConvertToTimeSpanString(object objTs)
        {
            if (objTs == null)
                return null;

            byte[] btTsArray = objTs as byte[];
            if (btTsArray == null)
                return null;

            string strTimeSpan = "0x" + BitConverter.ToString(btTsArray).Replace("-", "");
            return strTimeSpan;
        }

        #endregion

        #region---随机码---

        /// <summary>
        /// 根据时间生产流水号
        /// </summary>
        public static string GetDateCode(string Prefix)
        {
            string str = Prefix + DateTime.Now.ToString("yyyyMMddhhmmss");
            return str;
        }

        /// <summary>
        /// 随机码---真实随机数
        /// </summary>
        public static string RandCode()
        {
            int N = 8;
            char[] arrChar = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'S', 'B' };
            StringBuilder num = new StringBuilder();
            Random rnd = new Random(Guid.NewGuid().GetHashCode());
            for (int i = 0; i < N; i++)
            {
                num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());
            }
            return num.ToString();
        }
        public static int RandCodeInt(int N)
        {
            int[] arrInt = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1 };
            Random rnd = new Random(Guid.NewGuid().GetHashCode());
            int R = 0;
            for (int i = 0; i < N; i++)
            {
                R += arrInt[rnd.Next(0, arrInt.Length)];
            }
            return R;
        }

        /// <summary>
        /// 生成随机码---6位数字
        /// </summary>
        public static string RNGRandomStr()
        {
            byte[] randomBytes = new byte[4];
            RNGCryptoServiceProvider rngCrypto = new RNGCryptoServiceProvider();
            rngCrypto.GetBytes(randomBytes);
            int rngNum = BitConverter.ToInt32(randomBytes, 0);
            rngNum = (int)(Math.Abs(rngNum) / (decimal)int.MaxValue * (1000001));
            string result = rngNum.ToString().PadLeft(6, '0').Replace("-", "");
            return result;
        }
        /// <summary>
        /// 生成随机4位数字
        /// </summary>
        public static int RNGRandomInt()
        {
            byte[] randomBytes = new byte[4];
            RNGCryptoServiceProvider rngCrypto = new RNGCryptoServiceProvider();
            rngCrypto.GetBytes(randomBytes);
            int rngNum = BitConverter.ToInt32(randomBytes, 0);
            rngNum = (int)(Math.Abs(rngNum) / (decimal)int.MaxValue * (10001));
            return rngNum;
        }
        /// <summary>
        /// 生成含日期的唯一码
        /// </summary>
        public static string DateRandomGuid()
        {
            string G = Guid.NewGuid().ToString("N");
            string D = Get0Number(DateTime.Today.Year) + Get0Number(DateTime.Today.Month) + Get0Number(DateTime.Today.Day);
            return D + G;
        }
        public static string DateRandom()
        {
            string G = RNGRandomStr() + RNGRandomInt().ToString();
            string D = Get0Number(DateTime.Today.Year) + Get0Number(DateTime.Today.Month) + Get0Number(DateTime.Today.Day);
            return D + G;
        }
        private static string Get0Number(int i)
        {
            if (i > 99)
            {
                var j = i.ToString();
                return j.Substring(j.Length - 2, 2);
            }

            if (i < 10)
                return "0" + i.ToString();
            else
                return i.ToString();
        }

        #endregion

        #region---记录日志---

        private static object lockerObj = new object();
        private static FileLogHelper FLog = null;

        public static void WriteLog(string readme)
        {
            if (FLog == null)
            {
                lock (lockerObj)
                {
                    if (FLog == null)
                    {
                        string path = LogPath();
                        FLog = new FileLogHelper(path);
                    }
                }
            }

            if (FLog != null)
                FLog.WriteLine(readme);

        }
        public static void WriteLog(params string[] readmeLS)
        {
            if (readmeLS == null)
                return;

            if (readmeLS.Count() < 1)
                return;

            if (FLog == null)
            {
                lock (lockerObj)
                {
                    if (FLog == null)
                    {
                        string path = LogPath();
                        FLog = new FileLogHelper(path);
                    }
                }
            }

            if (FLog != null)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var readme in readmeLS)
                {
                    sb.Append("\r\n日志：" + readme + "\r\n操作时间：" + System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                }
                FLog.Write(sb.ToString());
                FLog.WriteLine("---End---");
            }
        }

        public static void RecordError(Exception ex)
        {
            if (FLog == null)
            {
                lock (lockerObj)
                {
                    if (FLog == null)
                    {
                        string path = LogPath();
                        FLog = new FileLogHelper(path);
                    }
                }
            }

            DateTime dt = DateTime.Now;
            StringBuilder log = new StringBuilder("");
            string time = dt.ToString("[yyyy-MM-dd HH:mm:ss]");
            if (ex != null)
            {
                log.Append("\r\n");
                log.Append(time + "\r\n");
                log.Append(ex.Message + "\r\n");
                log.Append(ex.Source + "\r\n");
                log.Append(ex.TargetSite + "\r\n");
                log.Append(ex.StackTrace + "\r\n");
            }

            if (FLog != null)
                FLog.Write(log.ToString());
        }

        /// <summary>
        /// 保存日志的文件夹
        /// </summary>
        public static string LogPath()
        {
            string logPath = string.Empty;
            logPath = AppContext.BaseDirectory + @"LogInfo\";

            if (!Directory.Exists(logPath))
                Directory.CreateDirectory(logPath);

            return logPath;
        }

        #endregion

        #region---字符串操作---

        /// <summary>
        /// 获取前几位数
        /// </summary>
        public static string GetFirstStr(string str, int num)
        {
            if (str.Length > num)
                str = str.Substring(0, num);

            return str;
        }

        /// <summary>
        /// 获取后几位数
        /// </summary>
        public static string GetLastStr(string str, int num)
        {
            int count = 0;
            if (str.Length > num)
            {
                count = str.Length - num;
                str = str.Substring(count, num);
            }
            return str;
        }

        /// <summary>
        /// 去除HTML的标签---提供截取
        /// </summary>
        public static string ReplaceHtmlTag(string html, int length = 0)
        {
            if (html.IsEmpty())
                return string.Empty;

            string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
            strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }

        /// <summary>
        /// 替换html中的特殊字符
        /// </summary>
        /// <param name="Str">需要进行替换的文本。</param>
        /// <returns>替换完的文本。</returns>
        public static string HtmlEncode(string Str)
        {
            if (string.IsNullOrEmpty(Str))
                return string.Empty;

            Str = Str.Replace(">", "&gt;");
            Str = Str.Replace("<", "&lt;");
            Str = Str.Replace(" ", "&nbsp;");
            Str = Str.Replace("  ", " &nbsp;");
            Str = Str.Replace("\t", "&nbsp;");
            Str = Str.Replace("\"", "&quot;");
            Str = Str.Replace("\'", "&apos;");
            Str = Str.Replace("\r\n", "<br/>");
            Str = Str.Replace("\n", "<br/>");
            Str = Str.Replace("\r", "<br/>");
            return Str;
        }
        /// <summary>
        /// 恢复html中的特殊字符
        /// </summary>
        /// <param name="Str">需要恢复的文本。</param>
        /// <returns>恢复好的文本。</returns>
        public static string HtmlDiscode(string Str)
        {
            if (string.IsNullOrEmpty(Str))
                return null;

            Str = Str.Replace("&gt;", ">");
            Str = Str.Replace("&lt;", "<");
            Str = Str.Replace("&nbsp;", "\t");
            Str = Str.Replace("&nbsp;", " ");
            Str = Str.Replace(" &nbsp;", "  ");
            Str = Str.Replace("&quot;", "\"");
            Str = Str.Replace("&apos;", "\'");
            Str = Str.Replace("<br/>", "\r\n");
            return Str;
        }

        /// <summary>
        /// 验证字符串是否是全英文
        /// </summary>
        public static bool HasAllEngByString(string Str)
        {
            if (string.IsNullOrEmpty(Str))
                return false;

            if (Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(Str)) == Str)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 验证字符串是否全中文
        /// </summary>
        public static bool HasALLChinaByString(string source)
        {
            Regex rg = new Regex("^[\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
            return rg.IsMatch(source);
        }

        /// <summary>
        /// 验证字符串是否是数字
        /// </summary>
        public static bool IsNumberic(string message, out int result)
        {
            Regex rex = new Regex(@"^\d+$");
            result = 0;
            if (rex.IsMatch(message))
            {
                result = int.Parse(message);
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">需要分割的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (string.IsNullOrEmpty(strContent))
            {
                return null;
            }
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">需要分割的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <returns></returns>
        public static List<string> SplitList(string strContent, char strSplit)
        {
            if (string.IsNullOrEmpty(strContent))
            {
                return new List<string>();
            }
            List<string> str = new List<string>();
            if (strContent.IndexOf(strSplit) == 0)
            {
                str.Add(strContent);
            }
            foreach (string s in Regex.Split(strContent, Regex.Escape(strSplit.ToString()), RegexOptions.IgnoreCase))
            {
                if (s.Length > 0)
                {
                    str.Add(s);
                }
            }
            return str;
        }
        /// <summary>
        /// 分割字符串int
        /// </summary>
        /// <param name="strContent">需要分割的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <returns></returns>
        public static List<int> SplitInt(string strContent, char strSplit)
        {
            if (string.IsNullOrEmpty(strContent))
            {
                return new List<int>();
            }
            List<int> str = new List<int>();
            if (strContent.IndexOf(strSplit) == 0)
            {
                str.Add(int.Parse(strContent));
            }
            foreach (string s in Regex.Split(strContent, Regex.Escape(strSplit.ToString()), RegexOptions.IgnoreCase))
            {
                if (s.Length > 0)
                {
                    str.Add(int.Parse(s));
                }
            }
            return str;
        }
        /// <summary>
        /// 分割字符串long
        /// </summary>
        /// <param name="strContent">需要分割的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <returns></returns>
        public static List<long> SplitLong(string strContent, char strSplit)
        {
            if (string.IsNullOrEmpty(strContent))
            {
                return new List<long>();
            }
            List<long> str = new List<long>();
            if (strContent.IndexOf(strSplit) == 0)
            {
                str.Add(long.Parse(strContent));
            }
            foreach (string s in Regex.Split(strContent, Regex.Escape(strSplit.ToString()), RegexOptions.IgnoreCase))
            {
                if (s.Length > 0)
                {
                    str.Add(int.Parse(s));
                }
            }
            return str;
        }

        /// <summary>
        /// 返回带连接的字符串
        /// </summary>
        public static string GetLinkUrl(object Str)
        {
            Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            return urlregex.Replace(Str.ToString(), "<a href=\"$1\" target=\"_blank\">$1</a>");
        }

        /// <summary>
        /// 字符串是否Json格式
        /// </summary>
        public static bool IsJsonStart(ref string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                json = json.Trim('\r', '\n', ' ');
                if (json.Length > 1)
                {
                    char s = json[0];
                    char e = json[json.Length - 1];
                    return (s == '{' && e == '}') || (s == '[' && e == ']');
                }
            }
            return false;
        }

        /// <summary>
        /// 截前后字符
        /// </summary>
        /// <param name="val">原字符串</param>
        /// <param name="c">要截取的字符</param>
        public static string GetInterceptString(string val, char c)
        {
            if (val.IsEmpty())
                return val;

            //---https://www.cnblogs.com/Jingkunliu/p/5336880.html---
            return val.TrimStart(c).TrimEnd(c);
        }

        #endregion

        #region---字符串64编解码---

        public static string Encode64(string Text)
        {
            var V = ConvertStringEncode(Text);
            return ConvertStringToBase64(V);
        }

        public static string Decode64Url(string Text)
        {
            string V = ConvertBase64ToString(HttpUtility.UrlDecode(Text));
            return ConvertStringDecode(V);
        }

        public static string Decode64(string Text)
        {
            string V = ConvertBase64ToString(Text);
            return ConvertStringDecode(V);
        }

        /// <summary>
        /// 双编码
        /// </summary>
        public static string ConvertStringEncode(string inputString)
        {
            string outputString = HttpUtility.UrlEncode(inputString);
            return Uri.EscapeDataString(outputString);
        }

        /// <summary>
        /// 双解码
        /// </summary>
        public static string ConvertStringDecode(string inputString)
        {
            string outputString = HttpUtility.UrlDecode(inputString);
            return Uri.UnescapeDataString(outputString);
        }

        /// <summary>
        /// 转64字符串
        /// </summary>
        public static string ConvertStringToBase64(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;

            byte[] byteArray = Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(byteArray);
        }

        /// <summary>
        /// 64转正常字符串
        /// </summary>
        public static string ConvertBase64ToString(string base64Str)
        {
            if (string.IsNullOrEmpty(base64Str))
                return string.Empty;

            byte[] bytes = Convert.FromBase64String(base64Str);
            return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        }

        #endregion

        #region---linq分页---

        /// <summary>
        /// 利用Linq分页操作一次性拿出分页后的结构数据
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="Ls">实体集合</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>分页后的结构数据</returns>
        public static List<List<T>> GetPagingResult<T>(List<T> Ls, int pageSize)
        {
            if (Ls == null)
                return null;

            if (pageSize < 1)
                return new List<List<T>>() { Ls };

            int pageNum = 0;    //页码
            var LLS = new List<List<T>>();
            while (pageNum * pageSize < Ls.Count)
            {
                //分页  
                var query = Ls.Skip(pageSize * pageNum).Take(pageSize);
                LLS.Add(query.ToList());
                pageNum++;
            }
            return LLS;
        }

        /// <summary>
        /// 缓存数据linq分页
        /// </summary>
        public static List<T> LinqByPage<T>(List<T> ALLData, int pageIndex, int pageSize, out int count) where T : class
        {
            count = 0;
            if (ALLData == null)
                return new List<T>();

            count = ALLData.Count;
            return ALLData.Count > 0 ? ALLData.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList() : new List<T>();
        }

        #endregion

        /// <summary>
        /// 序列化操作(将对象序列化为字节流)
        /// </summary>
        public static byte[] SerializeObject(object pObj)
        {
            if (pObj == null)
                return null;

            MemoryStream _memory = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(_memory, pObj);
            _memory.Position = 0;

            byte[] read = new byte[_memory.Length];
            _memory.Read(read, 0, read.Length);
            _memory.Close();

            return read;
        }

        /// <summary>
        /// 反序列化(将字节流反序列化为对象)
        /// </summary>
        public static object DeserializeObject(byte[] pBytes)
        {
            object _newOjb = null;
            if (pBytes == null)
                return _newOjb;

            try
            {
                MemoryStream _memory = new MemoryStream(pBytes);
                _memory.Position = 0;

                BinaryFormatter formatter = new BinaryFormatter();
                _newOjb = formatter.Deserialize(_memory);
                _memory.Close();
            }
            catch
            {
                _newOjb = null;
            }

            return _newOjb;
        }

        /// <summary>
        /// 获取宿主IP(不适用未知多网卡场景)
        /// </summary>
        public static string GetHostLocalIP()
        {
            string localIP = null;
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }

            return localIP;
        }

        /// <summary>
        /// 数字转中文
        /// </summary>
        public static string NumberToChinese(int number)
        {
            string res = string.Empty;
            string str = number.ToString();
            string schar = str.Substring(0, 1);
            switch (schar)
            {
                case "1":
                    res = "一";
                    break;
                case "2":
                    res = "二";
                    break;
                case "3":
                    res = "三";
                    break;
                case "4":
                    res = "四";
                    break;
                case "5":
                    res = "五";
                    break;
                case "6":
                    res = "六";
                    break;
                case "7":
                    res = "七";
                    break;
                case "8":
                    res = "八";
                    break;
                case "9":
                    res = "九";
                    break;
                default:
                    res = "零";
                    break;
            }
            if (str.Length > 1)
            {
                switch (str.Length)
                {
                    case 2:
                    case 6:
                        res += "十";
                        break;
                    case 3:
                    case 7:
                        res += "百";
                        break;
                    case 4:
                        res += "千";
                        break;
                    case 5:
                        res += "万";
                        break;
                    default:
                        res += "";
                        break;
                }
                res += NumberToChinese(int.Parse(str.Substring(1, str.Length - 1)));
            }
            return res;
        }

        /// <summary>
        /// 获取的文件夹
        /// </summary>
        public static string GetBinPath(string DirName)
        {
            string stsPath = string.Empty;
            stsPath = AppContext.BaseDirectory + @"\" + DirName + @"\";

            if (!Directory.Exists(stsPath))
                Directory.CreateDirectory(stsPath);

            return stsPath;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        public static void DeleteFile(string file)
        {
            if (File.Exists(file))
                File.Delete(file);
        }

        /// <summary>
        /// 格式化文本（防止SQL注入）
        /// </summary>
        public static string Formatstr(string html)
        {
            if (html.IsEmpty())
                return string.Empty;

            Regex regex1 = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" href *= *[\s\S]*script *:", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@" on[\s\S]*=", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<frameset[\s\S]+</frameset *>", RegexOptions.IgnoreCase);
            Regex regex10 = new Regex(@"select", RegexOptions.IgnoreCase);
            Regex regex11 = new Regex(@"update", RegexOptions.IgnoreCase);
            Regex regex12 = new Regex(@"delete", RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
            html = regex4.Replace(html, ""); //过滤iframe
            html = regex10.Replace(html, "s_elect");
            html = regex11.Replace(html, "u_pudate");
            html = regex12.Replace(html, "d_elete");
            html = html.Replace("'", "’");
            html = html.Replace("&nbsp;", " ");
            return html;
        }

    }
}
